﻿using PlutoStudio.Dependency;
using PlutoStudio.Runtime.Security;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PlutoStudio.Runtime.Session
{
    public class ClaimsSession : SessionBase,ISingletonDependency
    {
        public override int? UserId
        {
            get
            {
                if (OverridedValue != null)
                {
                    return OverridedValue.UserId;
                }

                var userIdClaim = PrincipalAccessor.Principal?.Claims.FirstOrDefault(c => c.Type == FrameworkClaimTypes.UserId);
                if (string.IsNullOrEmpty(userIdClaim?.Value))
                {
                    return null;
                }

                int userId;
                if (!int.TryParse(userIdClaim.Value, out userId))
                {
                    return null;
                }

                return userId;
            }
        }



        public override int? ImpersonatorUserId
        {
            get
            {
                var impersonatorUserIdClaim = PrincipalAccessor.Principal?.Claims.FirstOrDefault(c => c.Type == FrameworkClaimTypes.ImpersonatorUserId);
                if (string.IsNullOrEmpty(impersonatorUserIdClaim?.Value))
                {
                    return null;
                }

                return Convert.ToInt32(impersonatorUserIdClaim.Value);
            }
        }


        protected IPrincipalAccessor PrincipalAccessor { get; }

        public ClaimsSession(
            IPrincipalAccessor principalAccessor,
            IAmbientScopeProvider<SessionOverride> sessionOverrideScopeProvider)
            : base(
                  sessionOverrideScopeProvider)
        {
            PrincipalAccessor = principalAccessor;
        }
    }
}
